import { useState, useEffect } from "react";
import { Table, Button, Form, Space, Tag, Card } from "antd";
import { message } from "../../utils/customMessage";
import {
  EditOutlined,
  DeleteOutlined,
  ClockCircleOutlined,
  UserOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { http } from "../../utils/request";

interface UserData {
  id: string;
  username: string;
  fullName: string;
  email: string;
  tel: string;
  // 根据实际接口返回数据添加其他字段
}

interface TableParams {
  pagination: {
    current: number;
    pageSize: number;
  };
}

interface OperationLogItem {
  id: number;
  operatorEvent: string;
  operatorResult: string;
  operatorTime: string;
  operatorUser: string;
  operatorUserId: number;
}

interface ApiResponse {
  data: {
    current: number;
    pages: number;
    records: OperationLogItem[];
    size: number;
    total: number;
  };
  msg: string;
  status: number;
}

const UserManager = () => {
  const [data, setData] = useState<UserData[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 30,
    },
  });
  const [modalType, setModalType] = useState<"add" | "edit">("add");
  const [selectedUser, setSelectedUser] = useState<UserData | null>(null);
  const [dataSource, setDataSource] = useState<OperationLogItem[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`,
  });

  // 获取用户列表
  const fetchData = async () => {
    setLoading(true);
    try {
      const result = await http.get(
        `/api/user/userList?page=${tableParams.pagination.current}&pageSize=${tableParams.pagination.pageSize}`
      );

      setData(result.data);
      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: result.total,
        },
      });
    } catch (error) {
      message.error("获取用户列表失败");
    } finally {
      setLoading(false);
    }
  };

  // 获取操作日志列表
  const fetchOperationLogs = async (
    page: number = 1,
    pageSize: number = 10
  ) => {
    setLoading(true);
    try {
      const result: ApiResponse = await http.get(
        `/api/operator/operatorLogList?page=${page}&pageSize=${pageSize}`
      );

      if (+result.status === 200) {
        setDataSource(result.data.records);
        setPagination((prev) => ({
          ...prev,
          current: result.data.current,
          total: result.data.total,
          pageSize: result.data.size,
        }));
      } else {
        message.error(result.msg || "获取操作日志失败");
      }
    } catch (error) {
      console.error("获取操作日志失败:", error);
      message.error("获取操作日志失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    fetchOperationLogs();
  }, [tableParams.pagination.current, tableParams.pagination.pageSize]);

  // 表格列定义
  const columns: ColumnsType<UserData> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "姓名",
      dataIndex: "fullName",
      key: "fullName",
    },
    {
      title: "密码",
      dataIndex: "password",
      key: "password",
    },
    {
      title: "电话",
      dataIndex: "tel",
      key: "tel",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: number) => {
        const statusMap = {
          0: { text: "正常", color: "success" },
          1: { text: "锁定", color: "warning" },
          2: { text: "禁用", color: "error" },
        };
        const { text, color } = statusMap[status] || {
          text: "未知",
          color: "default",
        };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 处理表格变化
  const handleTableChange = (paginationConfig: any) => {
    const { current, pageSize } = paginationConfig;
    setTableParams({
      ...tableParams,
      pagination: {
        ...tableParams.pagination,
        current,
        pageSize,
      },
    });
    fetchData();
    fetchOperationLogs(current, pageSize);
  };

  // 修改更新用户的处理函数
  const handleUpdate = async (values: any) => {
    try {
      const result = await http.post("/api/user/update", {
        ...values,
        id: selectedUser?.id,
      });
      console.log(result);

      if (+result.status === 200) {
        message.success("更新用户成功");
        setIsModalVisible(false);
        form.resetFields();
        fetchData();
      } else {
        message.error(result.message || "更新用户失败");
      }
    } catch (error) {
      message.error("更新用户失败");
    }
  };

  // 修改编辑按钮的处理函数
  const handleEdit = (record: any) => {
    setModalType("edit");
    setSelectedUser(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  // 修改 Modal 的确认按钮处理函数
  const handleModalOk = () => {
    form.validateFields().then((values) => {
      if (modalType === "add") {
        handleAdd(values);
      } else {
        handleUpdate(values);
      }
    });
  };

  // 处理新增
  const handleAdd = async (values: any) => {
    try {
      await http.post("/api/user/save", values);
      message.success("添加成功");
      setIsModalVisible(false);
      form.resetFields();
      fetchData(); // 刷新数据
    } catch (error) {
      message.error("操作失败");
    }
  };

  // 处理删除
  const handleDelete = async (id: string) => {
    try {
      await http.post(`/api/user/del`, { id });
      message.success("删除成功");
      fetchData(); // 刷新数据
    } catch (error) {
      message.error("删除失败");
    }
  };

  // 获取操作结果标签颜色
  const getResultTagColor = (result: string): string => {
    const lowerResult = result.toLowerCase();
    if (lowerResult.includes("成功") || lowerResult.includes("success")) {
      return "success";
    }
    if (
      lowerResult.includes("失败") ||
      lowerResult.includes("error") ||
      lowerResult.includes("fail")
    ) {
      return "error";
    }
    if (lowerResult.includes("警告") || lowerResult.includes("warning")) {
      return "warning";
    }
    return "default";
  };

  // 表格列定义
  const operationColumns: ColumnsType<OperationLogItem> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 80,
    },
    {
      title: "操作用户",
      dataIndex: "operatorUser",
      key: "operatorUser",
      width: 120,
      render: (text: string, record: OperationLogItem) => (
        <div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
          <UserOutlined style={{ color: "#1890ff" }} />
          <span>{text}</span>
          <span
            style={{
              fontSize: "12px",
              color: "#8c8c8c",
              backgroundColor: "#f5f5f5",
              padding: "2px 4px",
              borderRadius: "4px",
            }}
          >
            ID:{record.operatorUserId}
          </span>
        </div>
      ),
    },
    {
      title: "操作事件",
      dataIndex: "operatorEvent",
      key: "operatorEvent",
      ellipsis: true,
      render: (text: string) => <span title={text}>{text}</span>,
    },
    {
      title: "操作结果",
      dataIndex: "operatorResult",
      key: "operatorResult",
      width: 120,
      render: (text: string) => (
        <Tag color={getResultTagColor(text)}>{text}</Tag>
      ),
    },
    {
      title: "操作时间",
      dataIndex: "operatorTime",
      key: "operatorTime",
      width: 180,
      render: (text: string) => (
        <div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
          <ClockCircleOutlined style={{ color: "#52c41a" }} />
          <span>{text}</span>
        </div>
      ),
    },
  ];

  return (
    <div
      style={{
        padding: "24px",
        backgroundColor: "#f5f5f5",
        minHeight: "100vh",
      }}
    >
      <Card
        title={
          <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
            <ClockCircleOutlined style={{ color: "#1890ff" }} />
            <span>操作日志</span>
          </div>
        }
        style={{
          borderRadius: "8px",
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
        }}
      >
        <Table
          columns={operationColumns}
          dataSource={dataSource}
          loading={loading}
          rowKey="id"
          pagination={{
            ...pagination,
            onChange: (page, pageSize) => {
              handleTableChange({ current: page, pageSize });
            },
            onShowSizeChange: (current, size) => {
              handleTableChange({ current: 1, pageSize: size });
            },
          }}
          scroll={{ x: 800 }}
          size="middle"
          style={{
            backgroundColor: "#fafafa",
            borderRadius: "6px",
          }}
        />

        <div
          style={{
            marginTop: "16px",
            fontSize: "12px",
            color: "#8c8c8c",
            backgroundColor: "#f9f9f9",
            padding: "12px",
            borderRadius: "4px",
            border: "1px solid #f0f0f0",
          }}
        >
          <div style={{ marginBottom: "4px" }}>
            <strong>说明：</strong>
          </div>
          <div>• 记录系统中所有用户的操作行为</div>
          <div>• 数据按后端默认顺序显示</div>
          <div>• 操作结果用不同颜色标签区分：成功(绿)、失败(红)、警告(橙)</div>
        </div>
      </Card>
    </div>
  );
};

export default UserManager;
